import { _decorator, Component, game, Node } from 'cc';
import { TelegramWebApp } from '../../cocos-telegram-miniapps/telegram-web';
import { WebTon } from '../../cocos-telegram-miniapps/webton';
import { TonConnectUi } from '../../cocos-telegram-miniapps/telegram-ui';
import { GlobalVar } from '../GlobalVar';
import { Config, config, TonAddressConfig } from '../Config';
import { GameEvent, PayEvent } from '../EventName';
const { ccclass, property } = _decorator;

@ccclass('TonConectionCom')
export class TonConectionCom extends Component {
    private _config: TonAddressConfig;


    protected onLoad(): void {
        
        game.on(PayEvent.TRANSFER_TON,this.sendTon,this);
        TelegramWebApp.Instance.init().then(res => {
            console.log("telegram web app init : ", res.success);
        }).catch(err => { console.error(err); });
        
        // this.loadWallet().then(res => {
        //     if (!res) {
        //         console.error('load wallet failed!')
        //         return;
        //     }
        // }).catch(err => { console.error(err); });
        this._initTonUI();
        WebTon.Instance.init().then(res => {
            console.log("web ton init : ", res.success);
        })
    }

     //open the wallet
     async loadWallet():Promise<boolean>{
        try{
      const value =await   fetch(`${config.backendUrl}/config`, {
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                "ngrok-skip-browser-warning":"1"
            },
            method: 'GET'}).then(response => {
            return response.json();
        })
        const addressConfig = {
            tonAddress: value.tokenRecipient,
            jettonAddress: value.jettonMaster
        } as TonAddressConfig;
        console.log(value.tokenRecipient,"ton收款地址")
          this._config = addressConfig;
        return true;
    }catch(e){

        console.error('request config failed!',e);
        return false;
    }
       
    }

    async _initTonUI() {
        //https://helizi2019.github.io/wallet
        TonConnectUi.Instance.init( Config.host +'/tonconnect-manifest.json',GlobalVar.receiveAddress, 'en').then(res => {
            console.log("ton connect ui init : ", res.success);
            TonConnectUi.Instance.subscribeWallet(()=>{
                console.log("wallet change");
                //EventManager.instance.emit(EventType.CONNECT_COMPLETE, res.success);
            })
        })
    }

     
    start() {

    }

    async sendTon(value?: string,comment?: string){


        if (!TonConnectUi.Instance._tgConnect) {

            console.log("tonconnect-ui 未初始化，无法拉起钱包")
            return;
        }

        if (TonConnectUi.Instance._tgConnect.connected) {
            
            let amount = TonConnectUi.Instance.toNano(value)
            await TonConnectUi.Instance.sendTransaction({
                amount: amount,
                  payload: await WebTon.Instance.createMessagePayload(comment),
                callBack: (result) => {
                 console.log('sendTon',result);
                 game.emit(GameEvent.SHOW_TOAST,result.result)
                 }
                 });

        } else {
            TonConnectUi.Instance.openModal();
        }

    }

    openWallet(){
        TonConnectUi.Instance.openModal();
    }

    update(deltaTime: number) {
        
    }
}


